package
{
	import com.common.queueloader.QueueLoader;
	import com.common.queueloader.QueueLoaderEvent;
	import com.common.queueloader.QueueVo;
	import com.common.utils.Reflection;
	import com.common.utils.TimeFrameUtil;
	import com.global.GlobalDef;
	import com.liangzhong.constants.NotificationConstants;
	import com.liangzhong.facade.GameFacade;
	import com.liangzhong.manager.ResourceManager;
	import com.liangzhong.model.AppData;
	import com.liangzhong.modules.login.mediator.LoginMediator;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.system.Security;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	import flash.ui.Keyboard;
	import flash.utils.getTimer;
	
	import lz.controls.Alert;
	
	import view.LoadingView;
	
	/**
	 * 55、d8obujbr0c6vcaujh8ukesiie7
	 56、d8obujbr0c6vcaujh8ukesiie8
	 57、d8obujbr0c6vcaujh8ukesiie9
	 58、d8obujbr0c6vcaujh8ukesiie0*
	 *  lake001    100010
		lake002    100011
		lake003    100012
		lake004    100013
		lake005    100014
	 * -swf-version=15
	 * -include-libraries "${DOCUMENTS}/GameFrame/bin/GameFrame.swc" "${DOCUMENTS}/GameInterface/bin/GameInterface.swc"
	 * 测试账号 
	 *  */ 
	[SWF(width="1024",height="600",backgroundColor="#000000",frameRate="25")]
	public class GameLoading extends Sprite
	{ 
		
		public var loadingView :LoadingView ;//进度条实例
		/**
		 * uid
		 */		
		private var uid :String;
		/**
		 * key
		 */		
		private var sid :String;
		/**
		 *新手设置状态
		 * 0 --- 未设置
		 * 1 --- 已设置 
		 */		
		private var guideStatus :int;
		/**
		 *资源路径
		 * 如为空则为配置中的路径 
		 */		
		private var resPath	:String = "";
		private var swfPath	:String = "";
		
		private var resources :Array = []; 
		/**
		 *是否加载完成 
		 */		
		private var isLoadComplete :Boolean = false;
		/**
		 *经过的时间总数 
		 */		
		private var totalPassTime :int;
		/**
		 *至少要显示loading时间 
		 */		
		private var showLoadingTime :int = 1000;
		/**
		 *引导片头动画时间 
		 */		
		private var showGuideStartTime :int = 24000;
		/**
		 *是否是引导 
		 */		
		private var isGuide			:Boolean = false;
		/**
		 *片头 
		 */		
		private var guideStartMc 		:MovieClip;
		
		public function GameLoading()
		{
			//平台接口数据
			var param :Object = stage.loaderInfo.parameters;
			uid = param.uid;
			sid = param.sid;
			guideStatus = int(param.guideStatus);
			resPath = param.path;
			swfPath = param.swfPath;
			///
			var v :String = param.v;
			if(v && v !== "")
			{
				GlobalDef.ReleaseVersion = v;
			}
			//test
			//GlobalDef.ReleaseVersion = new Date().getTime() + "";
			///
			GlobalDef.GameStage = this.stage;
			GlobalDef.StageWidth = this.stage.stageWidth;
			GlobalDef.StageHeight = this.stage.stageHeight;
			//GlobalDef.GameContainer = new Sprite();;
			//GlobalDef.GameStage.addChild(GlobalDef.GameContainer);
			//GlobalDef.AlertContainer = new Sprite();
			//GlobalDef.GameStage.addChild(GlobalDef.AlertContainer);
			GlobalDef.AlertContainer = new Sprite();
			GlobalDef.GameStage.addChild(GlobalDef.AlertContainer);
			GlobalDef.GameStage.stageFocusRect = false;
			GlobalDef.GameStage.align = StageAlign.TOP_LEFT;
			GlobalDef.GameStage.scaleMode = StageScaleMode.NO_SCALE;
			GlobalDef.GameStage.tabChildren = false;

			//this.stage.frameRate = 24;
			///浏览器最小化 帧频降低
			var sound:Sound = new Sound(new URLRequest(""));
			sound.play();
			sound.close(); 
			//
			this.loaderInfo.addEventListener(Event.COMPLETE,onMainComplete);
			///
			var myContextMenu :ContextMenu = new ContextMenu();
			var menuLabel :String = "版本：V " + v;
			var item:ContextMenuItem = new ContextMenuItem(menuLabel);
			myContextMenu.customItems.push(item);
			//myContextMenu.hideBuiltInItems();
			this.contextMenu = myContextMenu;
			//
			GlobalDef.GameStage.addEventListener(Event.RESIZE,onResizeHandler);
		}
		/**
		 *舞台大小改变 
		 * @param e
		 * 
		 */		
		private function onResizeHandler(e :Event):void
		{
			GlobalDef.StageWidth = this.stage.stageWidth;
			GlobalDef.StageHeight = this.stage.stageHeight;
			if(loadingView)
			{
				loadingView.x = (GlobalDef.GameStage.stageWidth - loadingView.width)/2;
				loadingView.y = (GlobalDef.GameStage.stageHeight - loadingView.height)/2;
			}
		}
		/**
		 *right click 
		 * 
		 */		
		public function onRightClick():void
		{
			onLogin();
		}
		/**
		 *自身加载完成 
		 * @param e
		 * 
		 */		
		private function onMainComplete(e :Event):void
		{
			if(swfPath !=null && swfPath!="")
			{
				QueueLoader.swfPath = swfPath;
			}
			var loader :QueueLoader = new QueueLoader();
			loader.addEventListener(QueueLoaderEvent.ITEM_COMPLETE,onLoadConfigItemComplete);
			loader.addEventListener(QueueLoaderEvent.QUEUE_COMPLETE,onLoadConfigQueueComplete);
			var releaseVersion :String = "?" + GlobalDef.ReleaseVersion;
			loader.addQueue(new QueueVo("loading","loading","loading"),"res/swf/loading/loading.swf" + releaseVersion + ".swf");
			loader.addQueue(new QueueVo("serverConfig","serverConfig","serverConfig"),"res/config/srvmap.xml" + releaseVersion  + ".xml");
			loader.addQueue(new QueueVo("resConfig","resConfig","resConfig"),"res/config/ResConfig.xml" + releaseVersion + ".xml");
			loader.queueLoadStart();
		}
		/**
		 *加载配置文件完成 
		 * @param e
		 */	
		private var lConfig :XML;
		private var nConfig :XML;
		private var preConfig :XML;
		private function onLoadConfigItemComplete(e:QueueLoaderEvent):void
		{
			if(e.queueVo == null)
			{
				return;
			}
			//保存资源
			resources.push(e.content);
			///解析
			var resConfig :XML;
			switch(e.queueVo.queueName)
			{
				case "loading":
				{
					///初始化loading
					loadingView = new LoadingView();;
					addChild(loadingView);
					loadingView.x = (GlobalDef.GameStage.stageWidth - loadingView.width)/2;
					loadingView.y = (GlobalDef.GameStage.stageHeight - loadingView.height)/2;
					break;
				}
				case "resConfig":
				{
					resConfig = XML(e.content);
					preConfig = resConfig;
					break;
				}
				case "serverConfig":
				{
					resConfig = XML(e.content);
					parseServerConfig(resConfig);
					break;
				}
			}
		}
		private function onLoadConfigQueueComplete(e :QueueLoaderEvent):void
		{
			starLoadData(preConfig);
			//
			//loadingView.totalBytes = int(preConfig.items.@totalBytes);
		}
		/**
		 *分析服务器配置信息 
		 * @param config
		 */	
		private var serverCount :int;
		private var serverList	 :XMLList ;
		private function parseServerConfig(config :XML):void
		{
			serverCount  = config.sock.@num;
			serverList  = config.sock.srv;
			var api_Host :String = config.rest.srv.@host;
			//var guide_Host :String = config.guide.srv.@host;
			var res_Host	:String = config.res.srv.@host;
			GlobalDef.Web_Api_Url = api_Host;
			//GlobalDef.Web_Guide_Url = guide_Host;
			GlobalDef.Web_Res_Url = res_Host;
			GlobalDef.Platform_Code = int(config.platform[0]);
			if(resPath != null && resPath != "")
			{
				GlobalDef.Web_Res_Url = resPath;
			}
		} 
		/**
		 *开始加载共享资源 
		 * 
		 */		
		private function starLoadData(config :XML):void
		{
			if(config == null)
			{
				return;
			}
			////加载过程
			var loader :QueueLoader = new QueueLoader();
			loader.addEventListener(QueueLoaderEvent.ITEM_COMPLETE,onItemComplete);
			loader.addEventListener(QueueLoaderEvent.ITEM_PROGRESS,onItemProgress);
			loader.addEventListener(QueueLoaderEvent.QUEUE_COMPLETE,onComplete);
			loader.addEventListener(QueueLoaderEvent.QUEUE_PROGRESS,onProgress);
			loader.addEventListener(QueueLoaderEvent.ITEM_HTTP_STATUS,onItemHttpStatus);
			loader.addEventListener(QueueLoaderEvent.ITEM_ERROR,onItemError);
			var releaseVersion :String;
			guideStatus = 1;
			/*if(guideStatus == 0)
			{
				releaseVersion = "?" + GlobalDef.ReleaseVersion + ".swf";
				loader.addQueue(new QueueVo("新手资源","Guide"),"res/swf/guide/Start_Intro.swf" + releaseVersion);
				isGuide = true;
			}*/
			releaseVersion = "?" + GlobalDef.ReleaseVersion + ".swf";
			loader.addQueue(new QueueVo("新手资源","Guide"),"res/swf/guide/guide_res.swf" + releaseVersion);
			if(guideStatus == 0)
			{
				releaseVersion = "?" + GlobalDef.ReleaseVersion + ".swf";
				loader.addQueue(new QueueVo("新手设置","Guide_Set"),"res/swf/guide/Player_Setting.swf" + releaseVersion);
			}
			//资源列表
			for each(var item :XML in config.items.item)
			{
				releaseVersion = "?" + GlobalDef.ReleaseVersion + "." + item.@itemType;
				loader.addQueue(new QueueVo(item.@resName,"",item.@id),item.@url + releaseVersion);
			}
			loader.queueLoadStart();
			///隐藏上下文菜单
			//var myContextMenu :ContextMenu = new ContextMenu();
			//this.contextMenu = myContextMenu;
			//this.contextMenu.hideBuiltInItems();
			//stage.showDefaultContextMenu = false;
		}
		/**
		 * 子进度
		 * @param e
		 * 
		 */		
		private function onItemProgress(e:QueueLoaderEvent):void
		{
			loadingView.totalBytes = e.bytesTotal;
			loadingView.loadedBytes = e.bytesLoaded;
			loadingView.content  = e.queueVo.queueName;
		}
		/**
		 * 子完成
		 * @param e
		 * 
		 */		
		private function onItemComplete(e:QueueLoaderEvent):void
		{
			resources.push(e.content);
			if(e.queueVo == null)
			{
				return;
			}
			///解析
			var resConfig :XML;
			switch(e.queueVo.queueId)
			{
				case "1007"://压缩资源包
				{
					//var tempTime :Number = getTimer();
					var zipList :Array = e.content;
					for each(var zipObj :Object in zipList)
					{
						resConfig = XML(zipObj.content);
						ResourceManager.instance.putResource(zipObj.name,resConfig);
					}
					//trace("use time:",getTimer() - tempTime);
					break;
				}
			}
		}
		/**
		 * 总进度
		 * @param e
		 * 
		 */		
		private function onProgress(e:QueueLoaderEvent):void
		{
			
		}
		/**
		 * 完成
		 * @param e
		 * 
		 */		
		private var loginMc:Object;
		private function onComplete(e:QueueLoaderEvent):void
		{
			isLoadComplete = true;
			startLogin();
			loadingView.content  = "正在连接服务器";
		}
		/**
		 *开始登录
		 * 
		 */		
		private function startLogin():void
		{
			if(guideStatus == 0)
			{
				AppData.getInstance().user.isGuideing = true;
			}
			//loadingView.content  = "正在连接服务器...";
			var facade :GameFacade = GameFacade.getInstance();
			facade.registerMediator(new LoginMediator(LoginMediator.MediatorName,this));
			//uid = "55";
			//sid = "d8obujbr0c6vcaujh8ukesiie7";
			AppData.getInstance().user.uid = Number(uid);
			if(sid == null)
			{
				sid = "";
			}
			AppData.getInstance().user.key = sid;
			AppData.getInstance().isLoadComplete = true;
			facade.sendNotification(NotificationConstants.Login_Loader_Complete);
			//
			/////////////////////////////////////////////////////////////////////////////
			
			if(contains(loadingView))
			{
				removeChild(loadingView);
			}
			loginMc = Reflection.createInstance("LoginMc");
			loginMc.x = (GlobalDef.StageWidth - loginMc.width)/2
			loginMc.y = (GlobalDef.StageHeight - loginMc.height)/2;
			//100006
			loginMc.txtUserId.text = "33621180";
			//loginMc.txtUserId.text = "100019";
			if(uid)
			{
				loginMc.txtUserId.text = uid;
			}
			loginMc.txtUserKey.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
			//loginMc.txtUserKey.text = "d8obujbr0c6vcaujh8ukeeeeee100019";
			if(sid)
			{
				loginMc.txtUserKey.text = sid;
			}
			this.addChild(loginMc as DisplayObject);
			
			loginMc.loginBtn.addEventListener(MouseEvent.CLICK,onLogin);
			addEventListener(KeyboardEvent.KEY_DOWN,inerFunc);
			function inerFunc(e:KeyboardEvent):void
			{
				switch(e.keyCode)
				{
					case Keyboard.ENTER:
					{
						removeEventListener(KeyboardEvent.KEY_DOWN,inerFunc)
						onLogin();
						break;
					}
				}
			}
			//系统初始化 连接server
			/*var userId :int = int(uid);
			var index :int = userId % serverList.length();
			AppData.getInstance().ip = serverList[index].@ip;
			AppData.getInstance().port = serverList[index].@port;
			var url :String = "xmlsocket://" + AppData.getInstance().ip + ":443";
			Security.loadPolicyFile(url);
			facade.startUp();*/
		}
		/**
		 * 沙箱安全问题
		 * @param e
		 * 
		 */		
		private function onItemHttpStatus(e :QueueLoaderEvent):void
		{
			//Alert.show("沙箱安全问题!","",Alert.YES,GlobalDef.GameStage);
			//loadingView.content  = "沙箱安全问题!";
		}
		/**
		 * 文件路径有误
		 * @param e
		 * 
		 */		
		private function onItemError(e :QueueLoaderEvent):void
		{
			//Alert.show("文件路径有误!","",Alert.YES,GlobalDef.GameStage);
			//loadingView.content  = "文件路径有误!";
		}
		private function onLogin(e:Event = null):void
		{
			/////
			//stage.displayState = StageDisplayState.FULL_SCREEN;//全屏显示
			//////
			var facade :GameFacade = GameFacade.getInstance();
			var userId :Number = Number(loginMc.txtUserId.text);
			var userKey :String = loginMc.txtUserKey.text;
			
			AppData.getInstance().user.uid = userId;
			AppData.getInstance().user.key = userKey;
			trace(loginMc.txtUserId.text);
			trace(loginMc.txtUserKey.text);
			//系统初始化 连接server
			var index :int = userId % serverList.length();
			AppData.getInstance().ip = serverList[index].@ip;
			AppData.getInstance().port = serverList[index].@port;
			var url :String = "xmlsocket://" + AppData.getInstance().ip + ":443";
			Security.loadPolicyFile(url);
			facade.startUp();
			trace(AppData.getInstance().ip,AppData.getInstance().port);
			//Alert.showErrorTip("人民币不足!美女不足!");
			//Debug.log(url);
			//Debug.log(url,6);
			////
			//var info :String = "userId = " + userId + " userKey = " + userKey + " logining...";
			//Debug.logError(userId,userKey,info);
		}
	}
}